package com.ihrm.controller;

import com.ihrm.common.controller.BaseController;
import com.ihrm.common.entity.Result;
import com.ihrm.common.entity.ResultCode;
import com.ihrm.domain.company.Company;
import com.ihrm.domain.company.Department;
import com.ihrm.domain.company.response.DeptListResult;
import com.ihrm.service.CompanyService;
import com.ihrm.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@RestController()
@RequestMapping("/company")
public class DepartmentController extends BaseController {

    @Autowired
    DepartmentService departmentService;

    @Autowired
    CompanyService companyService;

    @RequestMapping(value = "/departments", method = RequestMethod.POST)
    public Result add(@RequestBody Department department){
        department.setCompanyId(this.companyId);
        departmentService.save(department);
        return Result.SUCCESS();
    }

    @RequestMapping(value = "/departments/{id}", method = RequestMethod.PUT)
    public Result update(@PathVariable(name = "id") String id, @RequestBody Department department){
        department.setCompanyId(this.companyId);
        department.setId(id);
        departmentService.update(department);
        return Result.SUCCESS();
    }

    @RequestMapping(value = "/departments/{id}", method = RequestMethod.DELETE)
    public Result delete(@PathVariable(name = "id") String id){
        departmentService.delete(id);
        return Result.SUCCESS();
    }

    @RequestMapping(value = "/departments/{id}", method = RequestMethod.GET)
    public Result findById(@PathVariable(name = "id") String id){
        Department department = departmentService.findById(id);
        return new Result(ResultCode.SUCCESS, department);
    }

    @RequestMapping(value = "/departments", method = RequestMethod.GET)
    public Result findAll(){
        Company company = companyService.findById(this.companyId);
        List<Department> departmentList = departmentService.findAll(this.companyId);
        return new Result(ResultCode.SUCCESS, new DeptListResult(company, departmentList));
    }

}
